package com.mlog.njyjy.ndop.share.sql.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * resource loader util
 * </p>
 *
 * @author <a href="mailto:yingxiufeng@mlogcn.com">alex</a>
 * @version v1.0, 2020/7/9
 */
public final class ResourceLoaderUtil {

    private static final Logger log = LoggerFactory.getLogger(ResourceLoaderUtil.class);

    /**
     * 扫描资源文件路径
     */
    private static final List<String> SCAN_LOCATIONS = Collections.unmodifiableList(Arrays.asList("file:cfg/", "file:./config/", "file:./"
            , "classpath:/config/", "classpath:/"));

    private static final ResourceLoader LOADER = new DefaultResourceLoader();

    /**
     * load resource of data.json
     *
     * @return
     */
    public static Resource loadResource(String resourcePath) {
        Resource resource = null;
        for (String loc : SCAN_LOCATIONS) {
            resource = ResourceLoaderUtil.LOADER.getResource(loc.concat(resourcePath));
            if (resource.exists()) {
                break;
            } else {
                resource = null;
            }
        }
        if (resource == null) {
            log.warn(" cannot load resource [{}]", resourcePath);
            return null;
        }
        return resource;
    }
}
